﻿Imports Microsoft.TeamFoundation.Client
Imports Microsoft.TeamFoundation.WorkItemTracking.Client

Public Delegate Sub OnTeamProjectSelected(ByVal TeamProject As Project)

Public Class ProjectSelectionControl

    Public Event TeamProjectSelected As OnTeamProjectSelected

    Private m_TeamServer As TeamFoundationServer

    Public ReadOnly Property TeamServer() As TeamFoundationServer
        Get
            Return m_TeamServer
        End Get
    End Property

    Private m_Project As Project

    Public ReadOnly Property Project() As Project
        Get
            If m_Project Is Nothing Then
                If Not String.IsNullOrEmpty(My.Settings.TeamProject) Then
                    Dim WIT As WorkItemStore = DirectCast(TeamServer.GetService(GetType(WorkItemStore)), WorkItemStore)
                    m_Project = (From p As Project In WIT.Projects.Cast(Of Project)() Where p.Name = My.Settings.TeamProject).SingleOrDefault
                    RaiseEvent TeamProjectSelected(m_Project)
                End If
            End If
            Return m_Project
        End Get
    End Property

    Public Sub SetTeamServer(ByVal TeamServer As TeamFoundationServer)
        m_TeamServer = TeamServer
        BuildDDL()
    End Sub

    Private Sub SelectServerControl_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not TeamServer Is Nothing Then
            Me.ux_ComboBoxProject.Enabled = True
        End If
    End Sub


    Private Sub ux_ComboBoxTeamServers_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ux_ComboBoxProject.SelectedIndexChanged
        My.Settings.TeamProject = CStr(Me.ux_ComboBoxProject.SelectedItem)
        m_Project = Nothing
        Me.ux_ComboBoxProject.SelectedValue = Project.Name
    End Sub

    Private Sub BuildDDL()
        Me.ux_ComboBoxProject.Items.Clear()
        If Not TeamServer Is Nothing Then
            Me.ux_ComboBoxProject.Enabled = True
            Dim WIT As WorkItemStore = DirectCast(TeamServer.GetService(GetType(WorkItemStore)), WorkItemStore)
            For Each p As Project In WIT.Projects
                Me.ux_ComboBoxProject.Items.Add(p.Name)
            Next
            If Not Project Is Nothing Then
                Me.ux_ComboBoxProject.SelectedValue = Project.Name
            End If
        Else
            Me.ux_ComboBoxProject.Enabled = False
        End If
    End Sub


End Class
